﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using UIT.Controls;
#if !SILVERLIGHT
using UIT.WPF.Renderers;

namespace UIT.WPF
#else
using UIT.Silverlight.Renderers;

namespace UIT.Silverlight
#endif
{
    public static class Extensions
    {
        public static UIElement Render<T>(this RendererManager manager, T control)
            where T : IControl
        {
            return RenderWpf(manager.Control.GetRenderer((IControl)control), control);
        }

        public static UIElement Render<T>(this RendererManager manager, T control, Type type)
        where T : IControl
        {
            try
            {
                return RenderWpf(manager.Control.GetRenderer(type), control);
            }
            catch (KeyNotFoundException)
            {
                return Render<T>(manager, control);
            }
        }

        private static UIElement RenderWpf(IControlRenderer renderer, IControl control)
        {
            renderer.Render(control);
#if !SILVERLIGHT
            IWpfRenderer wpfRenderer = renderer as IWpfRenderer;
#else
            ISlRenderer wpfRenderer = renderer as ISlRenderer;
#endif
            if (wpfRenderer != null)
            {
                new DrawableControlRenderer(wpfRenderer.Result as FrameworkElement).Render(control);
                new ControlControlRenderer(wpfRenderer.Result as System.Windows.Controls.Control).Render(control);
                new Renderers.Specials.KeyBindingRenderer(wpfRenderer.Result).Render(control);
                return wpfRenderer.Result;
            }
            return null;
        }

    }
}
